package com.qlogic.commons.web;

import java.util.Collection;
import java.util.Iterator;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import com.qlogic.commons.exceptions.BaseException;
import com.qlogic.commons.kernel.Kernel;
import com.qlogic.commons.kernel.KernelException;
import com.qlogic.commons.kernel.ResourceProvider;
import com.qlogic.commons.resources.Resource;

/**
 * Servlet Class
 *
 * @web.servlet              name="ModuleStartup"
 *                           display-name="Name for ModuleStartup"
 *                           description="Description for ModuleStartup"
 * @web.servlet-mapping      url-pattern="/ModuleStartup"
 * @web.servlet-init-param   name="A parameter"
 *                           value="A value"
 *  <pre>                         
 *  The structure of META-INF directory :
 *  
 *         META-INF
 *            |
 *            + file {module}.xml (ex rdii.xml)
 *            |
 *            + <B>resources dir (optional)</B>
 *            |   |
 *            |   + resource file...
 *            |
 *            + <B>mappings</B>
 *            |   |
 *            |   + mapping file 1
 *            |   + mapping file 2
 *            |   + <B>subdir</B>
 *            |       |
 *            |       + mapping file 3
 *            + <B>queries</B>                 
 *                |
 *                + query file 1
 *                + query file 2
 *                + <B>subdir</B>
 *                    |
 *                    + query file 3
 *  </pre>                         
 */
public class ModuleStartupServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 7800622373294614589L;
	
	protected String resourcePath;

	private String MODULE_NAME = "com.qlogic.commons.web.moduleName";
	
	private String STARTUP_RESOURCES = "evaluated-resources";
	private String SHUTDOWN_RESOURCES = "shutdown-resources";
	
	public ModuleStartupServlet() {
		super();
	}
	
	protected String getModuleName () {
		String className = this.getClass ().getName ();
		String moduleName = className.substring (className.lastIndexOf ('.') + 1);
		moduleName = moduleName.substring (0, moduleName.indexOf ("StartupServlet")).toLowerCase ();
		return moduleName;
	}

	public void init (ServletConfig config) throws ServletException {
		super.init (config);
		String moduleName = config.getInitParameter (MODULE_NAME);
		if (moduleName == null) {
			moduleName = getModuleName ();
		}
		
		System.out.println ("\tStarting Module [" + moduleName + "]");
		
		try {
			ResourceProvider resourceProvider = (ResourceProvider)Kernel.getCurrentInstance().getFactory ().getInstance (ResourceProvider.class);
			resourceProvider.setFactory (Kernel.getCurrentInstance().getFactory ());
			resourceProvider.setRootResource (Kernel.getRootResource ());
			Kernel.getCurrentInstance().registerAddionalClassLoader (moduleName, Thread.currentThread().getContextClassLoader ());
			
			String moduleConfigFile = getServletContext().getRealPath("/META-INF/" + moduleName + ".xml");
			System.out.println ("\tModule Config file [" + moduleConfigFile + "]");
			
			resourcePath = resourceProvider.load (moduleConfigFile, Kernel.getCurrentInstance().getAdditionalClassLoaders(), Thread.currentThread().getContextClassLoader (), moduleName, null);
			
			Resource moduleResource = Kernel.getResource (resourcePath);
			evaluateResources (moduleResource, STARTUP_RESOURCES);
			
		} catch (BaseException e) {
			e.printStackTrace ();
			throw new ServletException (e);
		}
	}
	
	protected void evaluateResources (Resource moduleResource, String name) throws KernelException {
		Resource evalRes = null;
		try {
			evalRes = moduleResource.getResource (name);
		} catch (BaseException e) {
		}
		
		if (evalRes != null) {
			try {
				Collection servicePaths = (Collection)evalRes.getValue ();
				Iterator iterator = servicePaths.iterator();
				while (iterator.hasNext ()) {
					String servicePath = (String)iterator.next ();
					System.out.println ("\tEvaluation of ressource [" + servicePath + "]");
					Object value = moduleResource.getResource (servicePath.trim ()).getValue ();
					System.out.println ("\t\tResource [" + servicePath + "] evaluated to [" + value + "]");
				}
			} catch (Exception e) {
				throw new KernelException (e);
			}
		}
	}

	public void destroy () {
		try {
			Resource moduleResource = Kernel.getResource (resourcePath);
			evaluateResources (moduleResource, SHUTDOWN_RESOURCES);
		} catch (Exception e) {
			e.printStackTrace ();
		}
		super.destroy();
	}

}
